//
//  SelectContactListViewController.m
//  OAProject
//
//  Created by yhj on 2017/4/7.
//  Copyright © 2017年 cdnunion. All rights reserved.
//

#import "SelectContactListViewController.h"
#import "SectionHeadTableViewCell.h"
#import "RowDetailTableViewCell.h"
#import "XCAPIManager.h"
#import "TaskProgressModel.h"
#import "TaskListViewController.h"

static NSString *SectionHeadTableViewCellIdentifier=@"SectionHeadTableViewCellIdentifier";
static NSString *RowDetailTableViewCellIdentifier=@"RowDetailTableViewCellIdentifier";

@interface SelectContactListViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)UITableView *tableView;

@property(nonatomic, strong) NSMutableArray* models;                /* <所有数据模型> **/

@property(nonatomic, strong) NSArray* FBModels;                     /* <所有数据模型副本> **/

@property(nonatomic, strong) NSMutableDictionary* allSelections;    /* <全局字典，存放选择的所有状态数据> **/

@property(nonatomic, assign) BOOL isRotation;                       /* <判断组头是否收缩> **/

@property(nonatomic, strong) NSMutableArray* deleteSections;

@property(nonatomic,strong)NSMutableArray *groupIDArr;

@property(nonatomic,strong)NSMutableArray *userNameArr;

@property(nonatomic,strong)NSMutableArray *userIDArr;

@end

@implementation SelectContactListViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSLog(@"sdhjhsdhds00---%@",self.selectContactIDArr);


    if ([self.typeStr isEqualToString:@"turnOver"])
    {
       self.title=@"选择转接人";
    }
    else if ([self.typeStr isEqualToString:@"EditTaskProgress"])
    {
       self.title=@"选择负责人";
    }
    else
    {
        self.title=@"选择负责人";
    }


    self.groupIDArr=[NSMutableArray array];
    self.userIDArr=[NSMutableArray array];
    self.userNameArr=[NSMutableArray array];

    self.automaticallyAdjustsScrollViewInsets=NO;

     [self.view addSubview:self.tableView];

    [self GetGroupListData];

    self.tableView.mj_header=[MJRefreshNormalHeader
                              headerWithRefreshingBlock:^{
                                  [self GetGroupListData];
                              }];
    [self.tableView.mj_header beginRefreshing];

    [self selectContactData];

}


-(void)GetGroupListData
{
    [self.groupIDArr removeAllObjects];

    [self.models removeAllObjects];

    [self.deleteSections removeAllObjects];

    [self.allSelections removeAllObjects];


    // 获取下级部门及其用户列表
    @weakify(self)
    NSDictionary *params=@{
                           @"group_id":@"0",
                           @"return_type":@"0"
                           };

// test.api.vathome.cdnunion.com  test.api.vathome.cn
//// 测试的
//#define KContactUrl @"http://test.api.vathome.cdnunion.com/user/user/group"

// 正式的
#define KContactUrl @"http://api.vathome.cn/user/user/group"

    [[[[[[[XCAPIManager singleton] rac_POST:KContactUrl parameters:[params configParametersLevel_Users]] map:^id(id value) {

        NSLog(@"sdhjhdsjf666777----%@",value);

        if ([value[@"rt"] isEqual:@(1)])
        {
          return value[@"rows"];
        }
        else
        {
            [self.view makeToast:value[@"error"] duration:1 position:CSToastPositionCenter];
            return nil;
        }

    }] flattenMap:^RACStream *(NSArray* value) {
        if([value isKindOfClass:[NSError class]]){
            return [RACSignal return:value];
        }
        return [[XCAPIManager singleton] rac_MappingForClass:[FoldModel class] array:value];
    }] logError] replayLazily] subscribeNext:^(id x) {
        @strongify(self)

        [self.models addObjectsFromArray:x];

        self.FBModels = x;

        [self.groupIDArr removeAllObjects];
        
        for (FoldModel* model in self.models)
        {
            NSLog(@"sdhjhshdfh---%@",self.selectContactIDArr);

            //初始化空字典
            NSMutableArray* userArray=[NSMutableArray array];
            for (UsersModel* userModel in model.users){

                for (NSString *userID in self.selectContactIDArr) {
                    NSString *user_id=[NSString stringWithFormat:@"%ld",(long)userModel.user_id];
                    if ([user_id isEqualToString:userID]) {
                        [userArray addObject:userModel];
                        break;
                    }
                }
            }
            [self.allSelections setObject:userArray forKey:[NSString stringWithFormat:@"%lu",model.group_id]];
              [self.groupIDArr addObject:[NSString stringWithFormat:@"%ld",(long)model.group_id]];
            NSLog(@"sdjjjdf---%@",self.allSelections);

        }
//        {
//            //初始化空字典
//            [self.allSelections setObject:@[] forKey:[NSString stringWithFormat:@"%lu",(long)model.group_id]];
//
//            NSLog(@"DSJSDHJHDFJ--%@",self.allSelections);
//
//
//            [self.groupIDArr addObject:[NSString stringWithFormat:@"%ld",(long)model.group_id]];
//        }

        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];

    }];
}

-(void)selectContactData
{
    [self.userIDArr removeAllObjects];
    [self.userNameArr removeAllObjects];

    [AppUI initNavigationItem:self.navigationItem andWithText:@"确  定" andTextColor:WhiteColor andIsRight:YES withBlock:^{

        NSLog(@"sdshjhjfdhas23232323---%@",self.allSelections);

        // 所有已选择的分组数组
        NSMutableArray *sectionArr=[NSMutableArray array];
        for (int i=0;i<self.groupIDArr.count;i++)
        {
            id rowArr=self.allSelections[self.groupIDArr[i]];

            NSLog(@"sdhyhdfhfdh---%@",rowArr);

            if ([rowArr isKindOfClass:[NSString class]])
            {

            }
            else if ([rowArr isKindOfClass:[NSArray class]])
            {
                if ([rowArr count]>0)
                {
                    [sectionArr addObject:rowArr];
                }
            }

            NSArray *rowArr1=self.allSelections[self.groupIDArr[i]];

            NSLog(@"sdgghdfd8---%@  ----%@",rowArr1,self.groupIDArr[i]);



        }

        NSLog(@"sdsdsd9090----%@",sectionArr);


        // 所有已选择的数组
        NSMutableArray *selectArr=[NSMutableArray array];
        for (NSInteger i=0;i<sectionArr.count;i++)
        {
            for (UsersModel *model in sectionArr[i])
            {
                [selectArr addObject:model];
            }
        }

        for (int i=0;i<selectArr.count;i++)
        {
            UsersModel *model=selectArr[i];
            [self.userNameArr addObject:model.user_name];
            [self.userIDArr addObject:[NSString stringWithFormat:@"%ld",(long)model.user_id]];
        }

        // 选择转接人
        if ([self.typeStr isEqualToString:@"turnOver"])
        {
            if (self.userIDArr.count==0)
            {
                [self.view makeToast:@"请选择转接人" duration:1 position:CSToastPositionCenter];
            }
            else
            {
                NSLog(@"sdjkdsjkds---%@  ----%@  -----%@",self.userIDArr,self.userNameArr,self.userIDArr[0]);

                if (self.userNameArr.count>1)
                {
                    [self.view makeToast:@"转接人只能选择一个" duration:1 position:CSToastPositionCenter];
                    [self.userNameArr removeAllObjects];
                    [self.userIDArr removeAllObjects];
                    
                }
                else
                {
                    UIAlertView *alert=[UIAlertView alertViewWithTitle:@"你确定要转接给" message:self.userNameArr[0] cancelButtonTitle:@"取消" didDismissBlock:^(UIAlertView *alertView,NSInteger buttonIndex) {

                        if (buttonIndex==0)
                        {
                            [API DealTaskWithTaskID:self.taskID ac:@"turnover" turnID:self.userIDArr[0] memo:@"" success:^(id res) {

//                                NSLog(@"sdhjshdsd0--%@  0---%@",res,res[@"error"]);

                                if ([res[@"rt"] isEqual:@(1)])
                                {
                                    [self.view makeToast:@"转接成功" duration:1 position:CSToastPositionCenter];
                                    //[self.navigationController popViewControllerAnimated:NO];
                                    // 返回到任务列表界面
                                    for (UIViewController *vc in self.navigationController.viewControllers)
                                    {
                                        if ([vc isKindOfClass:[TaskListViewController class]])
                                        {
                                            [self.navigationController popToViewController:vc animated:NO];
                                        }
                                    }

                                }
                                else
                                {
                                    [self.view makeToast:res[@"error"] duration:1 position:CSToastPositionCenter];
                                }
                                
                            } failure:^(NSInteger stateCode) {
                                
                            }];
                        }
                    } otherButtonTitles:@"确定", nil];
                    [alert show];
                }
            }
        }
        // 编辑流程 修改负责人
        else if ([self.typeStr isEqualToString:@"EditTaskProgress"])
        {
            if (self.userIDArr.count==0)
            {
                [self.view makeToast:@"请选择负责人" duration:1 position:CSToastPositionCenter];
            }
            else
            {
                if (self.delegate && [self.delegate respondsToSelector:@selector(selectContactUserNameArr:userIDArr:)]) {
                    [self.delegate selectContactUserNameArr:self.userNameArr userIDArr:self.userIDArr];
                    [self.navigationController popViewControllerAnimated:NO];
                }
            }
        }
        // 选择负责人
        else
        {
            if (self.userIDArr.count==0)
            {
                [self.view makeToast:@"请选择负责人" duration:1 position:CSToastPositionCenter];
            }
            else
            {
                if (self.delegate && [self.delegate respondsToSelector:@selector(selectContactUserNameArr:userIDArr:)]) {
                    [self.delegate selectContactUserNameArr:self.userNameArr userIDArr:self.userIDArr];
                    [self.navigationController popViewControllerAnimated:NO];
                }
            }
        }
    }];
}

// tableView
-(UITableView *)tableView
{
    if (!_tableView) {
        _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0,64,APPW,APPH-64) style:UITableViewStylePlain];
        _tableView.dataSource=self;
        _tableView.delegate=self;
        _tableView.backgroundColor=MAIN_BACK_COLOR;
        _tableView.showsVerticalScrollIndicator=NO;
        _tableView.separatorStyle=UITableViewCellSeparatorStyleSingleLine;
        _tableView.tableFooterView=[UIView new];
        [self.tableView registerClass:[SectionHeadTableViewCell class] forCellReuseIdentifier:SectionHeadTableViewCellIdentifier];
        [self.tableView registerClass:[RowDetailTableViewCell class] forCellReuseIdentifier:RowDetailTableViewCellIdentifier];
    }
    return _tableView;
}


#pragma mark - Delegate Method
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.models.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray* details = ((FoldModel*)self.models[section]).users;
    return details.count + 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (0 == indexPath.row)
    {
        SectionHeadTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:SectionHeadTableViewCellIdentifier];
        cell.backgroundColor=BGColor;
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        [cell configModel:self.FBModels[indexPath.section] andBlock:^(UITableViewCell* cell,FoldModel *model, BOOL isSelectAll) {
            if ([self.allSelections[[NSString stringWithFormat:@"%lu",(long)model.group_id]] isEqual:@"空"]) {
                return ;
            }
            NSMutableArray* rows = [NSMutableArray arrayWithArray:self.allSelections[[NSString stringWithFormat:@"%lu",(long)model.group_id]]];
            [rows removeAllObjects];
            //TODO:全选处理
            if (isSelectAll && ((FoldModel*)self.models[indexPath.section]).users.count <= 0) {
                ((UIButton*)[[tableView cellForRowAtIndexPath:indexPath] viewWithTag:998]).transform = CGAffineTransformMakeRotation(0);

                [self.models replaceObjectAtIndex:indexPath.section withObject:[self addUsers:((FoldModel*)self.models[indexPath.section]).group_id]];

                NSMutableArray* deleteCells = [NSMutableArray array];
                for (NSInteger index = 0; index < ((FoldModel*)self.models[indexPath.section]).users.count; index++) {
                    [deleteCells addObject:[NSIndexPath indexPathForRow:index + 1 inSection:indexPath.section]];
                }
                [tableView insertRowsAtIndexPaths:deleteCells withRowAnimation:UITableViewRowAnimationTop];
            }

            for (NSInteger index = 0; index < model.users.count; index++) {
                isSelectAll ? [rows addObject:model.users[index]] : [rows removeObject:model.users[index]];;

                ((UIButton*)[[tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:index + 1 inSection:[tableView indexPathForCell:cell].section]] viewWithTag:999]).selected = isSelectAll;
            }
            [self.allSelections setObject:rows forKey:[NSString stringWithFormat:@"%lu",(long)model.group_id]];

            if (isSelectAll) {
                if (rows.count==0) {
                    [self.allSelections setObject:@"空" forKey:[NSString stringWithFormat:@"%ld",(long)model.group_id]];
                }
            }
//            NSLog(@"组全选结果:%@",self.allSelections);
        }];

        ((UIButton*)[cell viewWithTag:999]).selected = NO;
        for (FoldModel* foldModel in self.FBModels) {
            if (foldModel.group_id == cell.model.group_id) {
                if (foldModel.users.count > 0)
                {
                    if (foldModel.users.count == [self.allSelections[[NSString stringWithFormat:@"%lu",(long)cell.model.group_id]] count]) {
                        ((UIButton*)[cell viewWithTag:999]).selected = YES;
                    }
                }
                else
                {
                    if ([self.allSelections[[NSString stringWithFormat:@"%lu",(long)cell.model.group_id]] isEqual:@"空"]) {
                        ((UIButton*)[cell viewWithTag:999]).selected = YES;
                    }
                }
            }
        }
        
        return cell;
    }
    else
    {
        RowDetailTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:RowDetailTableViewCellIdentifier];
        ((UIButton*)[cell viewWithTag:999]).selected = NO;

        [cell configModel:((FoldModel*)self.FBModels[indexPath.section]).users[indexPath.row - 1] andBlock:^( UITableViewCell* cell,UsersModel *model, BOOL isSelectRow) {
            NSMutableArray* rows = [NSMutableArray arrayWithArray:self.allSelections[[NSString stringWithFormat:@"%lu",(long)model.group_id]]];

            if (isSelectRow) {
                [rows addObject:model];
                //判断组头是否勾选
                if (rows.count == ((FoldModel*)self.FBModels[[tableView indexPathForCell:cell].section]).users.count) {
                    ((UIButton*)[[tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:[tableView indexPathForCell:cell].section]] viewWithTag:999]).selected = YES;
                }
//                NSLog(@"选择了%@ userId:%lu userName:%@",model.group_name,(long)model.user_id, model.user_name);
            }else{
                [rows removeObject:model];
                //组头必须取消勾选，因为有一个取消选择
                ((UIButton*)[[tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:[tableView indexPathForCell:cell].section]] viewWithTag:999]).selected = NO;
//                NSLog(@"取消选择了%@ userId:%lu userName:%@",model.group_name,(long)model.user_id, model.user_name);
            }
            [self.allSelections setObject:rows forKey:[NSString stringWithFormat:@"%lu",(long)model.group_id]];

//            NSLog(@"结果:%@",self.allSelections);
        }];

        for (UsersModel* model in self.allSelections[[NSString stringWithFormat:@"%lu",(long)cell.model.group_id]]) {
            if (model.user_id == cell.model.user_id) {
                ((UIButton*)[cell viewWithTag:999]).selected = YES;
            }
        }

        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (0 == indexPath.row)
    {
//        NSLog(@"你点击了第%lu组头",(long)indexPath.section);

        NSMutableArray* deleteCells = [NSMutableArray array];

        if (((FoldModel*)self.models[indexPath.section]).users.count > 0) {
            ((UIButton*)[[tableView cellForRowAtIndexPath:indexPath] viewWithTag:998]).transform = CGAffineTransformMakeRotation(-M_PI/2);
            for (NSInteger index = 0; index < ((FoldModel*)self.models[indexPath.section]).users.count; index++) {
                [deleteCells addObject:[NSIndexPath indexPathForRow:index + 1 inSection:indexPath.section]];
            }

            FoldModel* model = self.FBModels[indexPath.section];
            FoldModel* foldModel = [[FoldModel alloc] init];
            foldModel.group_id = model.group_id;
            foldModel.group_name = model.group_name;
            foldModel.users = [@[] copy];
            [self.models replaceObjectAtIndex:indexPath.section withObject:foldModel];

            [tableView deleteRowsAtIndexPaths:deleteCells withRowAnimation:UITableViewRowAnimationTop];
        }
        else
        {
            ((UIButton*)[[tableView cellForRowAtIndexPath:indexPath] viewWithTag:998]).transform = CGAffineTransformMakeRotation(0);

            [self.models replaceObjectAtIndex:indexPath.section withObject:[self addUsers:((FoldModel*)self.models[indexPath.section]).group_id]];

            for (NSInteger index = 0; index < ((FoldModel*)self.models[indexPath.section]).users.count; index++) {
                [deleteCells addObject:[NSIndexPath indexPathForRow:index + 1 inSection:indexPath.section]];
            }

            [tableView insertRowsAtIndexPaths:deleteCells withRowAnimation:UITableViewRowAnimationTop];
        }
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==0)
    {
        return kmargin*5;
    }
    else
    {
        return kmargin*6;
    }
}


#pragma mark - Private Method
- (FoldModel*)addUsers:(NSInteger)groupId
{
    FoldModel* foldModel = [[FoldModel alloc] init];
    for (FoldModel* model in self.FBModels) {
        if (groupId == model.group_id) {
            foldModel.users = [model.users copy];
            foldModel.group_id = model.group_id;
            foldModel.group_name = model.group_name;
            break;
        }
    }
    return foldModel;
}

#pragma mark - Setter/Getter
- (NSMutableDictionary *)allSelections
{
    if (!_allSelections) {
        _allSelections = [NSMutableDictionary dictionary];
    }
    return _allSelections;
}

- (NSMutableArray *)deleteSections
{
    if (!_deleteSections) {
        _deleteSections = [NSMutableArray array];
    }
    return _deleteSections;
}

- (NSMutableArray *)models
{
    if (!_models) {
        _models = [[NSMutableArray alloc] init];
    }
    return _models;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat sectionHeaderHeight = 50;
    if(scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0)
    {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y,0,0,0);
    }
    else if (scrollView.contentOffset.y>=sectionHeaderHeight)
    {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight,0,0,0);
    }
}

// 间隙置边
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{

    if ([tableView respondsToSelector:@selector(setSeparatorInset:)])
    {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }

    if ([tableView respondsToSelector:@selector(setLayoutMargins:)])
    {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }

    if ([cell respondsToSelector:@selector(setLayoutMargins:)])
    {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

@end
